package com.tt.payee.service.sysuser.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tt.payee.business.AbortException;
import com.tt.payee.business.BusinessException;
import com.tt.payee.common.Constant;
import com.tt.payee.domain.SysUser;
import com.tt.payee.domain.dto.SysUserParam;
import com.tt.payee.domain.vo.SysUserVo;
import com.tt.payee.mapper.SysUserMapper;
import com.tt.payee.service.sysuser.SysUserService;
import com.tt.payee.utils.CreateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author：mingzheng.chen@comeon365.com
 * @date:2020/3/18 11:12
 */
@Slf4j
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";

    @Override
    public PageInfo<SysUserVo> getUsersByRules(Integer currentPage, Integer pageSize, SysUserParam sysUserParam) {

        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(sysUserParam, sysUser);

        PageHelper.startPage(currentPage, pageSize);

        if(StringUtils.isNotEmpty(sysUserParam.getBirthdayEndDate())){
            sysUserParam.setBirthdayEndDate(sysUserParam.getBirthdayEndDate() + " 23:59:59");
        }

        if(StringUtils.isNotEmpty(sysUserParam.getRegistryEndDate())){
            sysUserParam.setRegistryEndDate(sysUserParam.getRegistryEndDate() + " 23:59:59");
        }

        List<SysUserVo> users = sysUserMapper.getUsersByRules(sysUser, sysUserParam.getRegistryStartDate(),
                sysUserParam.getRegistryEndDate(), sysUserParam.getBirthdayStartDate(),
                sysUserParam.getBirthdayEndDate(), sysUserParam.getLabelId());

        return new PageInfo<>(users);
    }

    @Override
    public PageInfo<SysUserVo> getUsersByPages(Integer currentPage, Integer pageSize) {


        PageHelper.startPage(currentPage, pageSize);

        List<SysUserVo> sysUserVoList = sysUserMapper.getAllUsersWithLabel();

        return new PageInfo<>(sysUserVoList);
    }

    @Override
    public List<Map> getAllUsersToListMap() {
        //获取所有用户
        List<SysUser> sysUserList = sysUserMapper.getAllUsers();
        //声明将用户类变成kv映射的map
        List<Map> sysUserListMap = new ArrayList<>();

        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);

        //遍历所有用户生成映射map
        for (SysUser user : sysUserList) {
            Map<String, String> userMap = new HashMap<>();

            userMap.put("uid", Integer.toString(user.getUid()));
            userMap.put("userName", user.getUsername());
            userMap.put("name", user.getName());
            if(user.getSex() != null){
                userMap.put("sex", Integer.toString(user.getSex()));
            }
            if(null != user.getBirthday()){
                userMap.put("birthday", sdf.format(user.getBirthday()));
            }
            userMap.put("area", user.getArea());
            userMap.put("vip", user.getVip() == 1 ? "是" : "否");
            userMap.put("isEngineer", user.getIsEngineer() == 1 ? "是" : "否");
            userMap.put("point", String.valueOf(user.getPoint()));
            userMap.put("loginDate", sdf.format(user.getLogindate()));
            userMap.put("remark", user.getRemark());
            userMap.put("wxUnionId", user.getWxUnionid());
            userMap.put("wxOpenId", user.getWxOpenid());
            userMap.put("wxName", user.getWxName());
            userMap.put("status", user.getStatus() == 1 ? "正常" : "删除");
            userMap.put("registryDate", sdf.format(user.getCreated()));

            //添加进结果List
            sysUserListMap.add(userMap);
        }

        return sysUserListMap;
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Integer updateUserPoint(Integer uid, Integer type, Double point, String message) {

        //查询用户
        SysUser sysUser = sysUserMapper.getUserByUid(uid);

        //判断是否有该用户
        if (sysUser == null) {
            return 0;
        }

        int addPointLogRes = 0;
        int updateRes = 0;


        if (addPointLogRes == 1 && updateRes == 1) {
            return 1;
        }

        return 0;
    }

    @Override
    public Integer editUserStatus(Integer uid) {

        return  sysUserMapper.updateUserStatus(uid,Constant.USER_STATUS_DELETE);
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Integer editUserRemark(Integer uid, String remark) {

        int res = 0;

        try {
            res = sysUserMapper.updateUserRemark(uid, remark);
        } catch (Exception e) {
            log.error("修改用户备注失败" + e.getMessage());
            throw new RuntimeException();
        }

        return res;
    }

    @Override
    public int referralNumRefreshJob() {
        return sysUserMapper.updateUnrefereedNam();
    }

    /**
     * 查询信息
     *
     * @param uId Long
     * @return 信息
     */
    @Override
    public SysUser getById(Long uId) {
        return sysUserMapper.selectByPrimaryKey(uId);
    }

    /**
     * 查询一个信息
     *
     * @return 信息
     */
    @Override
    public SysUser getOne(SysUser sysUser)
    {
        return sysUserMapper.selectOne(sysUser);
    }

    /**
     * 新增
     *
     * @param sysUser ${classname} 信息
     * @return 结果
     */
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public SysUser insert(SysUser sysUser) {

        sysUser.setReferralCode(CreateCodeUtils.getRandomCode(8));

        SysUser tempUser = new SysUser();
        tempUser.setReferralCode(sysUser.getReferralCode());
        int isExist = sysUserMapper.selectCount(tempUser);
        while(isExist>0){
            sysUser.setReferralCode(CreateCodeUtils.getRandomCode(8));
            tempUser.setReferralCode(sysUser.getReferralCode());
            isExist = sysUserMapper.selectCount(tempUser);
        }

        sysUser.setStatus(1);
        int result = sysUserMapper.insertSelective(sysUser);
        if(result>=1){
            return sysUser;
        }
        return null;
    }

    /**
     * 修改权限表
     *
     * @param sysUser TbPermission 权限表信息
     * @return 结果
     */
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int update(SysUser sysUser) {

        SysUser tempUser = sysUserMapper.selectByPrimaryKey(sysUser.getUid());
        if(tempUser == null){
            throw new AbortException("获取数据失败");
        }
        //tempUser.setBackendUrl(sysUser.getBackendUrl());
        int result = sysUserMapper.updateByPrimaryKeySelective(sysUser);

        return result;
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int changeAttr(SysUser sysUser) {
        SysUser user = sysUserMapper.selectByPrimaryKey(sysUser.getUid());
        if(user == null){
            throw new AbortException("用户id错误");
        }

        int result = sysUserMapper.updateByPrimaryKeySelective(sysUser);
        return result;
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public SysUser changeWxPhone(SysUser sysUser) {

        //查找是否已存在手机号的用户
        SysUser searchUser = new SysUser();
        searchUser.setUsername(sysUser.getUsername());
        searchUser = sysUserMapper.selectOne(searchUser);
        if(searchUser!=null && StringUtils.isNotBlank(searchUser.getWxUnionid())){
            throw new AbortException("该手机号已授权到其他账号");
        }

        //
        //如果电话号码已存在，但是没有登录过小程序
        if(searchUser!=null && StringUtils.isBlank(searchUser.getWxUnionid())){
            //修改旧用户的username，比较积分后删除新账号
            if(searchUser.getPoint().compareTo(sysUser.getPoint())<0){
                searchUser.setPoint(sysUser.getPoint());
            }

            //修改旧账号，绑定unionId和openId
            searchUser.setWxUnionid(sysUser.getWxUnionid());
            searchUser.setWxOpenid(sysUser.getWxOpenid());
            searchUser.setWxName(sysUser.getWxName());
            sysUserMapper.updateByPrimaryKeySelective(searchUser);

            //删除新账号
            sysUser.setStatus(-1);
            sysUser.setUsername(sysUser.getUsername()+"-1");
            sysUser.setWxUnionid("");
            sysUser.setWxOpenid("");
            sysUserMapper.updateByPrimaryKeySelective(sysUser);

            return searchUser;
        }

        //修改用户手机号
        SysUser editUser = new SysUser();
        editUser.setUid(sysUser.getUid());
        editUser.setUsername(sysUser.getUsername());
        sysUserMapper.updateByPrimaryKeySelective(editUser);

        return sysUser;
    }
}
